package com.cookies.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tools.StringUtil;

public class SetCookiesServlet extends HttpServlet {

	private static final long serialVersionUID = 6320051782039143431L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String username = request.getParameter("username");
		String outputContent=null;
		if (!StringUtil.validateIsNull(username)) {
			Cookie cookie1 = new Cookie("username", StringUtil
					.filterHtml(username));
			cookie1.setMaxAge(24 * 60 * 30);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Cookie cookie2 = new Cookie("lastVisited", sdf
					.format(new java.util.Date()));
			cookie2.setMaxAge(24 * 60 * 30);
			response.addCookie(cookie1);
			response.addCookie(cookie2);
			outputContent="本次登陆的用户名与时间已经写到Cookie中。<br><a href='/test/getCookies'>读取Cookie</a><br>";
		}else
		{
			outputContent="用户名为空，请重新输入<br><a href='/test/cookieInput.html'>重新输入</a><br>";
		}
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
		out.println("<HTML>");
		out.println("  <HEAD><TITLE>setCookies</TITLE></HEAD>");
		out.println("  <BODY>");
		out.print("<h2>"+outputContent+"</h2><br>");
		out.println("  </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

}
